package com.jwkj.collector.modbus.request;


import com.jwkj.collector.modbus.base.ModbusFunction;
import com.jwkj.collector.modbus.util.ByteUtils;

/**
 * 多笔写入命令
 */
public class OneWriteRequest extends MultiWriteRequest {

    /**
     * 单笔写入
     *
     * @param addr         设备地址
     * @param registerAddr 寄存器地址
     */
    public OneWriteRequest(byte addr, int registerAddr, int value) {
        super(addr, ModbusFunction.ONE_WRITE, registerAddr, new int[]{value});
    }

    /**
     * @param buf
     */
    public OneWriteRequest(byte[] buf) {
        super(buf);
    }

    /**
     * 单笔写入解码<br/>
     * 和多笔写入的区别是省略了寄存器个数和字节长度
     */
    @Override
    protected void decode(byte[] buf) {
        //start
        this.registerAddr = ByteUtils.bytes2Int(buf, 0, 2);
        //length
        this.length = 1;
        //values
        this.values = new int[this.length];
        int value = ByteUtils.bytes2Int(this.datas, 2, 2);
        this.values[0] = value;
    }

    /**
     * 单笔写入编码<br/>
     * 和多笔写入的区别是省略了寄存器个数和字节长度
     */
    @Override
    protected byte[] encode() {
        //寄存器数量
        byte[] datas = new byte[4];
        //start
        byte[] startBytes = ByteUtils.int2Bytes(this.getRegisterAddr(), 2);
        datas[0] = startBytes[0];
        datas[1] = startBytes[1];
        //value
        byte[] valueBytes = ByteUtils.int2Bytes(this.getValues()[0], 2);
        datas[2] = valueBytes[0];
        datas[3] = valueBytes[1];

        return datas;
    }

}
